#! /usr/bin/env python
#coding=utf-8

import os
import sys
sys.path.append(os.path.join(os.path.dirname(os.path.realpath(__file__)), "../"))

from utils import ResterHelper
from utils import ResterStringBuilder

class NamedThreadResults(ResterStringBuilder):
	NAMED_THREAD_KEYS = ("name", "threads", "processes")
	THREAD_INFO_KEYS = ("tid", "thread", "pid", "process")
	def __init__(self, keys, row):
		for idx, key in enumerate(keys):
			self[key] = row[idx]

	def getStr(self, xargs=None, keys=None):
		if xargs and "details" in xargs:
			ordered_keys = NamedThreadResults.THREAD_INFO_KEYS
		else:
			ordered_keys = NamedThreadResults.NAMED_THREAD_KEYS
		return ResterStringBuilder.getStr(self, xargs, ordered_keys)

class NamedThreadsRestMgr(object):
	def __init__(self, product):
		self._product = product

	def get_all(self, xargs=None):
		if xargs and "details" in xargs:
			keys = NamedThreadResults.THREAD_INFO_KEYS
			sqlcmd = "select %s from threads_details" % ", ".join(keys)
		else:
			keys = NamedThreadResults.NAMED_THREAD_KEYS
			sqlcmd = "select %s from named_threads order by threads DESC" % ", ".join(keys)
			print(sqlcmd)
		cursor = self._product.getCursor()
		cursor.execute(sqlcmd)

		processes = []
		for row in cursor:
			processes.append(NamedThreadResults(keys, row))
		return processes

	def doRestRequest(self, id, mod, args):
		mCmdMap = {
			'threads':self._dbGetThreadsByName
		}
		vals = mCmdMap[mod](id, args)
		args["details"] = 1
		return ResterHelper.build_array_content(vals, args)

	def _dbGetThreadsByName(self, id, args):
		keys = NamedThreadResults.THREAD_INFO_KEYS
		sqlcmd = 'select %s from threads_details where thread="%s" order by process' % (", ".join(keys), id)
		cursor = self._product.getCursor()
		cursor.execute(sqlcmd)

		objects = []
		for row in cursor:
			objects.append(NamedThreadResults(keys, row))
		return objects

if __name__ == "__main__":
	import products

	product_mgr = products.Products()
	prod = product_mgr.get_product_by_name("openharmony", "rk3568")
	prod.load_db()

	mgr = ProcessesRestMgr(prod)

	#print(mgr._dbGetProcessObjects(1, {}))
	#print(mgr._dbGetProcessVmas(1, {}))

	print(mgr.doRestRequest(1, "objects", {}))

